const Promise = require('bluebird');
const moment = require('moment');

module.exports = function ({Users, Auths, UsersAmounts, LoginLogs, sequelize}) {

    /**
     * 统计分析 V2
     */
    Users.analyseV2 = function () {
        let sql = "select status, count(*) count from Users group by status";
        return sequelize.query(sql, {
            type: sequelize.QueryTypes.SELECT
        });
    }

    /**
     * 用户总数和活跃用户数
     */
    Users.analyseTotalV2 = function () {
        let start = moment().subtract(30, 'days').toDate();
        return Promise.props({
            count: Users.count(),
            active: Users.count({where: {last_order: {$gt: start}}})
        });
    }

    /**
     * 更新邀请数量
     */
    Users.updateInviteCountV2 = function (user_id) {
        // let sql = "update Users s, (select count(*) as count from Users where inviter_id = :user_id) u set s.invite_count = u.count where s.id = :user_id";
        // return sequelize.query(sql, {
        //     replacements: {user_id: user_id}
        // }).spread(function (res) {
        //     if (!res.affectedRows) {
        //         return {success: false};
        //     }
        //     return {success: true};
        // });

        return Users.count({where: {inviter_id: user_id}}).then(function (count) {
            return Users.update({invite_count: count}, {where: {id: user_id}}).then(function () {
                return {success: true};
            });
        });
    }

    /**
     * 更新下级代理数
     */
    Users.updateAgencyCountV2 = function (user_id) {
        return Users.count({where: {inviter_id: user_id, level: ['Agency', 'Partner']}}).then(function (count) {
            return Users.update({agency_count: count}, {where: {id: user_id}}).then(function () {
                return {success: true};
            });
        });
    }

    /**
     * 更新粉丝数量
     */
    Users.updateMemberCountV2 = function (user_id) {
        return Users.count({where: {$or: {inviter_id: user_id, agency_id: user_id}}}).then(function (count) {
            return Users.update({member_count: count}, {where: {id: user_id}}).then(function () {
                return {success: true};
            });
        });
    }

    /**
     * 用户登录 V2
     */
    Users.loginV2 = function ({tel, password, is_admin}) {
        let where = {tel: tel, status: 'Active'};
        if (is_admin) {
            where.role = {$ne: 'User'};
        }
        return Users.findOne({
            where: where,
            attributes: ['id', 'unionid', 'openid', 'tel', 'nickname', 'username', 'image']
        }).then(function (user) {
            if (!user) return {success: false, message: '账号不存在或不可用'};

            return Auths.validateV2({user_id: user.id, password: password}).then(function (result) {
                if (result.success) {
                    result.data = user;
                }
                return result;
            });
        });
    }

    /**
     * 用户注册 V2
     */
    Users.registerV2 = function (body) {
        return Promise.resolve().then(function () {
            let inviter_id = body.inviter_id;
            if (inviter_id) {
                return Users.findOne({where: {id: inviter_id}}).then(function (inviter) {
                    if (!inviter) {
                        delete body.inviter_id;
                    } else {
                        if (inviter.level == 'Partner') {
                            body.partner_id = inviter.id;
                            body.agency_id = inviter.id;
                        } else if (inviter.level == 'Agency') {
                            body.partner_id = inviter.partner_id;
                            body.agency_id = inviter.id;
                        } else {
                            body.partner_id = inviter.partner_id;
                            body.agency_id = inviter.agency_id;
                        }
                    }
                });
            }
        }).then(function () {
            if (!body.partner_id) {
                body.partner_id = 1;
            }
            if (!body.agency_id) {
                body.agency_id = 1;
            }

            return sequelize.transaction(function (t) {
                //创建用户
                return Users.create(body, {transaction: t}).then(function (user) {
                    //创建密码
                    if (body.password) {
                        return Auths.addV2({
                            auth: {user_id: user.id, password: body.password},
                            t: t
                        }).then(function () {
                            return {success: true, data: user};
                        });
                    }
                    return {success: true, data: user.dataValues || user};
                }).then(function (result) {
                    if (body.inviter_id) {
                        Users.updateInviteCountV2(body.inviter_id);
                    }
                    if (body.agency_id) {
                        Users.updateMemberCountV2(body.agency_id);
                    }
                    return result;
                });
            });
        });
    }

    /**
     * 删除用户 V2
     */
    Users.removeV2 = function (id) {
        return sequelize.transaction(function (t) {
            return Auths.destroy({where: {user_id: id}, transaction: t}).then(function () {
                return Users.destroy({where: {id: id}, transaction: t});
            }).then(function () {
                return {success: true};
            });
        }).catch(function (e) {
            if (e) {
                console.error('\n', e.stack || e.message);
            }
            return {success: false, message: e.message || ''};
        });
    }

    /**
     * 清除用户session, 修改密码, 禁用用户时 V2
     */
    Users.cleanUserSessionV2 = function ({id, redisClient}) {
        return LoginLogs.findAll({where: {is_void: 0, user_id: id}, limit: 50, raw: true}).then(function (logs) {
            return Promise.mapSeries(logs, function (log) {
                return new Promise(function (resolve) {

                    console.log('sess:' + log.sid);
                    redisClient.del('sess:' + log.sid, function (err) {
                        if (err) {
                            console.error('\n', err.stack || err.message);
                            return resolve({success: false});
                        }
                        LoginLogs.update({is_void: 1}, {where: {id: log.id}});
                        return resolve({success: true});
                    });
                });
            }, {concurrency: 1}).then(function () {
                return {success: true};
            });
        });
    }
}